package com.hqd.ch03.v37.context.validation;

import com.hqd.ch03.v37.beans.TypeConverter;
import com.hqd.ch03.v37.beans.converter.ConversionService;
import com.hqd.ch03.v37.beans.property.PropertyEditorRegistry;
import com.hqd.ch03.v37.beans.property.support.SimpleTypeConverter;
import com.hqd.ch03.v37.core.MethodParameter;
import com.sun.corba.se.impl.io.TypeMismatchException;
import lombok.Data;

import java.beans.PropertyEditor;
import java.lang.reflect.Field;

@Data
public class DataBinder implements PropertyEditorRegistry, TypeConverter {
    public static final int DEFAULT_AUTO_GROW_COLLECTION_LIMIT = 256;
    private Object target;
    private String objectName;
    private SimpleTypeConverter typeConverter;
    private ConversionService conversionService;
    // BindingResult：绑定错误、失败的时候会放进这里来~
    // 默认忽略不能识别的字段~
    private boolean ignoreUnknownFields = true;
    // 不能忽略非法的字段（比如我要Integer，你给传aaa，那肯定就不让绑定了，抛错）
    private boolean ignoreInvalidFields = false;
    // 默认是支持级联的~~~
    private boolean autoGrowNestedPaths = true;
    private int autoGrowCollectionLimit = DEFAULT_AUTO_GROW_COLLECTION_LIMIT;
    // 这三个参数  都可以自己指定~~ 允许的字段、不允许的、必须的
    private String[] allowedFields;
    private String[] disallowedFields;
    private String[] requiredFields;

    @Override
    public <T> T convertIfNecessary(Object value, Class<T> requiredType) {
        return getTypeConverter().convertIfNecessary(value, requiredType);
    }

    @Override
    public <T> T convertIfNecessary(Object value, Class<T> requiredType, MethodParameter methodParam) throws TypeMismatchException {
        return null;
    }

    @Override
    public <T> T convertIfNecessary(Object value, Class<T> requiredType, Field field) throws TypeMismatchException {
        return null;
    }

    @Override
    public void registerCustomEditor(Class<?> requiredType, PropertyEditor propertyEditor) {

    }

    @Override
    public PropertyEditor findCustomEditor(Class<?> requiredType) {
        return null;
    }

    @Override
    public PropertyEditor findCustomEditor(Class<?> requiredType, String propertyPath) {
        return null;
    }

    protected PropertyEditorRegistry getPropertyEditorRegistry() {
        return getSimpleTypeConverter();
    }

    protected SimpleTypeConverter getSimpleTypeConverter() {
        if (this.typeConverter == null) {
            this.typeConverter = new SimpleTypeConverter();
            if (this.conversionService != null) {
                this.typeConverter.setConversionService(this.conversionService);
            }
        }
        return this.typeConverter;
    }

    public void setConversionService(ConversionService conversionService) {
        this.conversionService = conversionService;
    }

    protected TypeConverter getTypeConverter() {
        return getSimpleTypeConverter();
    }


    public Object getTarget() {
        return target;
    }
}
